﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using Toolkit.Web.Validation;

namespace Toolkit.Web.Mvc.Validation
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class EmailAddressAttribute : ValidationAttribute
    {
        public EmailAddressAttribute()
        {
        }

        public bool AllowErrorMessageOverride
        {
            get;
            set;
        }

        protected string ErrorMessageOverride
        {
            get;
            private set;
        }

        public override bool IsValid(object value)
        {
            EmailAddressValidator emailAddressValidator = new EmailAddressValidator(value as string);
            string result = emailAddressValidator.Validate();

            if (result != null && !string.IsNullOrEmpty(result) && AllowErrorMessageOverride)
            {
                // Set error message if a default message has not been given.
                ErrorMessageOverride = result;
            }

            return (result == null);
        }

        public override string FormatErrorMessage(string name)
        {
            if (AllowErrorMessageOverride && !string.IsNullOrEmpty(ErrorMessageOverride))
            {
                return ErrorMessageOverride;
            }
            return base.FormatErrorMessage(name);
        }
    }
}
